<template>
  <div class="main">
    <div class="form_content">
      <NScrollbar>
        <NSpin :show="spinShow">
          <div class="content">
            <!-- 总评优秀人员 -->
            <div class="fixedPeople">
              <NScrollbar>
                <span>已选择总评优秀{{ selectPeopleName.length }}/{{ assessInfo?.excellentNum }}人</span>
                <div class="name">
                  <span v-for="(item, index) in selectPeopleName" :key="index"
                    :style="{ textAlign: (index + 1) % 3 == 0 ? 'right' : (index + 1) % 3 == 1 ? 'left' : 'center' }">
                    {{ item }}</span>
                </div>
              </NScrollbar>
            </div>
            <!-- 考核说明 -->
            <div class="topTitle">考核投票页面</div>
            <div class="centerRemark">
              <NIcon size="20" class="iconStyle">
                <ErrorRound />
              </NIcon>
              <div class="spanStyle">考核说明:</div>
              <div style="white-space: pre-wrap;flex: 1;" v-html="assessInfo?.remark"></div>
            </div>
            <!-- 列表 -->
            <div class="bottomTable">
              <!-- 顶部nav -->
              <div class="tableNav">
                <div class="nav1">一键选择</div>
                <div class="nav1" v-for="(_, index) in 5">
                  <n-radio-group v-model:value="seleteRadio[index]" @update:value="(merit) => handleRadio(merit, index)">
                    <n-radio v-for="item in radioList" :key="item.value" :value="item.value">
                      {{ item.label }}
                    </n-radio>
                  </n-radio-group>
                </div>
                <div class="nav2"></div>
              </div>
              <div class="tableType">
                <div class="nav1" v-for="(item, index) in typeList" :key="index">{{ item }}</div>
                <div class="nav2">总评</div>
              </div>
              <!-- 内容 -->
              <div class="tableType" v-for="(item, index) in appraisePeopleList">
                <div class="nav1">{{ index + 1 }}-{{ handleDeptName(item.deptName) }}-{{ item.name }}</div>
                <div class="nav1" v-for="(i, _) in arrKey">
                  <n-radio-group v-model:value="appraisePeopleList[index][i]">
                    <n-radio v-for="item in radioList" :key="item.value" :value="item.value">
                      {{ item.label }}
                    </n-radio>
                    <div class="errorText" v-if="appraisePeopleList[index][`${i}error`]">请选择评级</div>
                  </n-radio-group>
                </div>
                <div class="nav2">
                  <n-radio-group v-model:value="appraisePeopleList[index].appraise"
                    @update-value="(e) => handleAllApp(e, index)">
                    <n-radio v-for="item in resultRadioList" :key="item.value" :value="item.value">
                      {{ item.label }}
                    </n-radio>
                    <div class="errorText" v-if="appraisePeopleList[index][`appraiseerror`]">请选择总评等级</div>
                  </n-radio-group>
                </div>
              </div>
            </div>
          </div>
        </NSpin>
      </NScrollbar>
    </div>
  </div>

  <FixedAction>
    <div style="display: flex">
      <NSpace justify="start" style="flex: 0 0 42%">
        <NButton style="width: 78px; color: #5fb17f" ghost @click="goBack">
          <template #icon>
            <img :src="VBackImg" style="width: 25rem; height: 25rem" />
          </template>
          返回
        </NButton>
      </NSpace>

      <NSpace justify="center">
        <NButton style="width: 120px;" type="primary" @click="confirm()" :loading="loading" v-if="assessInfo?.scopeId">
          提交
        </NButton>
      </NSpace>
    </div>
  </FixedAction>

  <NModal :auto-focus="false" v-model:show="contentVisible" @close="contentVisible = false">
    <VDialogContent @close="contentVisible = false" @submit="submit" title="保存提示">
      <div style="width: 300rem; height: 100rem; text-align: center; ">
        本次考核测评以匿名方式进行，一旦提交后不允许重复提交或者二次更改，请谨慎填写并提交!
      </div>
    </VDialogContent>
  </NModal>
</template>
<script setup lang="ts">
import { NSpace, NButton, NScrollbar, useMessage, NSpin, NRadio, NRadioGroup, NIcon, NModal } from 'naive-ui'
import router from '@/router'
import { useRoute } from 'vue-router'
import { ref, watch } from 'vue'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import VBackImg from '@/assets/images/back.png'
import { ErrorRound } from '@vicons/material'
import { useViewerStore } from '@/views/OA/Common/store'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { aes } from '@/utils/crypto'

const useStore = useViewerStore()
const tags = useTagStore().tags
const route = useRoute()
const message = useMessage()
const seleteRadio: any = ref([null, null, null, null, null]) //一键选择的5个数据判断
const radioList = [{ label: '优', value: '0' }, { label: '良', value: '1' }, { label: '差', value: '2' }] //非总评类型
// 总评类型
const resultRadioList = [
  { label: '优秀', value: '0' }, { label: '合格', value: '1' },
  { label: '基本合格', value: '2' }, { label: '不合格', value: '3' }
]
const arrKey = ['morals', 'ability', 'toil', 'merit', 'integrity'] //不带总评字段的key
const arrKeyAll = ['morals', 'ability', 'toil', 'merit', 'integrity', 'appraise'] //带总评字段的key
const typeList = ['姓名/类型', '德', '能', '勤', '绩', '廉'] //类型
const selectPeopleName: any = ref([]) //被选择总评为优秀的人员名单
const contentVisible = ref(false)

// 确定
const submit = async () => {
  const tmp = JSON.parse(JSON.stringify(appraisePeopleList.value))
  tmp.map((it: any) => (delete it.deptName, delete it.name))
  const [error, res] = await sendRequest({
    module: 'assess',
    api: 'assessVote',
    override: {
      data: tmp
    }
  })
  if (error) return message.error(error.message), loading.value = false, contentVisible.value = false
  if (res.code != 0) return message.error(res.msg), loading.value = false, contentVisible.value = false
  message.success('保存成功')
  goBack()
}
// 提交
const loading = ref(false)
const errorFlag = ref(false)
const confirm = async () => {
  loading.value = true
  errorFlag.value = true
  // every 是否全部填写
  const flag =
    appraisePeopleList.value.every((it: any) => it.morals && it.ability && it.toil && it.merit && it.integrity && it.appraise)
  if (flag) contentVisible.value = true
  else {
    appraisePeopleList.value.map((it: any) => arrKeyAll.map((c: any) => it[c] ? it[`${c}error`] = false : it[`${c}error`] = true))
    message.error('有未选择评价，请检查并评价后重新提交')
  }
  loading.value = false
}
// 一键选择
const handleRadio = (v: any, i: any) => {
  seleteRadio.value[i] = v
  appraisePeopleList.value.map((it: any) => it[arrKey[i]] = v)
}
// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  tags.splice(index, 1)
  if (tags.length == 0) return router.push({ path: '/OA/Workbench/UserDesktop' })
  else history.back()
}
// 部门
const bbgDeptList: any = ref([])
const getBbgDeptList = async () => {
  const [error, res] = await sendRequest({
    module: 'overTime',
    api: 'BbgDeptList'
  })
  if (error || res.code != 0) return
  bbgDeptList.value = res.data
}
// 处理data
const handlePeopleList = () => {
  spinShow.value = true
  const tmp: any = []
  assessInfo.value.appraisePeopleList.map((it: any) => {
    tmp.push({
      staffAppraise: it.identifyingId,
      deptName: it.parentId?.split('-')[1], name: it.typeName,
      scopeId: assessInfo.value.scopeId,
      appraiseId: assessInfo.value.id
    })
  })
  appraisePeopleList.value = tmp
  spinShow.value = false
}
// 处理部门名称
const handleDeptName = (id: any) => bbgDeptList.value.find((it: any) => it.value == id)?.name
// 总评选择
const handleAllApp = (v: any, index: any) => {
  appraisePeopleList.value[index].appraise = v
  const tmp: any = []
  const resultName: any = []
  appraisePeopleList.value.forEach((it: any) => tmp.push(it['appraise']))
  tmp.forEach((it: any, index: any) => it == '0' ? resultName.push(appraisePeopleList.value[index].name) : null)
  if (resultName.length > assessInfo.value.excellentNum) setTimeout(() => appraisePeopleList.value[index].appraise = null, 0)
}
// 获取详情
// 获取数据
const spinShow = ref(false)
const appraisePeopleList: any = ref([])
const assessInfo: any = ref({})
const getAssessInfo = async () => {
  spinShow.value = true
  const [error, res] = await sendRequest({
    module: 'assess',
    api: 'assessInfo',
    uri: {
      id: route.params.appraiseId as never
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  assessInfo.value = res.data
  assessInfo.value.scopeId = route.params?.appraiseId
}

watch(() => appraisePeopleList, () => {
  var tmp: any = { morals: [], ability: [], toil: [], merit: [], integrity: [], appraise: [] }
  // 普通类型选择
  appraisePeopleList.value.forEach((it: any) => Object.keys(tmp).forEach((ability: any) => tmp[ability].push(it[ability])))
  Object.keys(tmp).forEach((ability: any, index: any) => {
    const flag1 = tmp[ability]?.length ? tmp[ability].every((it: any) => it == '0') : false
    const flag2 = tmp[ability]?.length ? tmp[ability].every((it: any) => it == '1') : false
    const flag3 = tmp[ability]?.length ? tmp[ability].every((it: any) => it == '2') : false
    if (flag1) seleteRadio.value[index] = '0'
    else if (flag2) seleteRadio.value[index] = '1'
    else if (flag3) seleteRadio.value[index] = '2'
    else seleteRadio.value[index] = null
  })
  // 总评选择判断人数大小
  const resultName: any = []
  tmp.appraise.forEach((it: any, index: any) => {
    if (((resultName.length + 1) > assessInfo.value.excellentNum) && it == '0')
      message.error(`总评优秀人数最多为${assessInfo.value.excellentNum}人，您已选择${assessInfo.value.excellentNum}人，不可多选`)
    else if (it == '0') resultName.push(appraisePeopleList.value[index].name)
  })
  selectPeopleName.value = resultName
  // 是否显示红色判断
  if (errorFlag.value) appraisePeopleList.value.map((it: any) =>
    arrKeyAll.map((c: any) => it[c] ? it[`${c}error`] = false : it[`${c}error`] = true))
}, { deep: true, immediate: true })

watch(
  () => route,
  async () => {
    if (route.name == 'OA/Assess/VoteInfo' && route.params?.appraiseId != 'null') {
      await getAssessInfo()
      assessInfo.value.scopeId = route.query?.scopeId || null
      handlePeopleList()
      getBbgDeptList()
    } else if (route.name == 'OA/Assess/VoteInfo' && route.params?.appraiseId == 'null') {
      assessInfo.value.appraisePeopleList = useStore.appraisePeopleList
      assessInfo.value.excellentNum = useStore.excellentNum
      assessInfo.value.remark = useStore.remark
      assessInfo.value.scopeId = useStore.scopeId
      assessInfo.value.appraiseId = useStore.appraiseId
      handlePeopleList()
    }
  },
  { deep: true, immediate: true }
)
</script>
<style scoped lang="scss">
@mixin CommonFont {
  font-size: 18rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: #333333;
}

@mixin CommonNav {
  display: flex;
  justify-content: center;
  align-items: center;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .form_content {
    width: 100%;
    height: 100%;
    padding: 20rem 20rem 0;

    .content {
      position: relative;
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 100%;
      height: 100%;
      padding: 18rem 33rem 120rem;
      overflow-y: scroll;
      background-color: #ebeceb;
      @include CommonFont;

      .fixedPeople {
        position: fixed;
        top: 150px;
        right: 45px;
        width: 210px;
        height: 300px;
        background-color: #00895b;
        padding: 10px;
        color: #ffffff;
        z-index: 99;

        span {
          font-size: 17px;
        }

        .name {
          display: flex;
          justify-content: flex-start;
          flex-wrap: wrap;
          margin-top: 8px;
          font-size: 15px;
          color: #cce6dd;
          text-align: center;

          span {
            font-size: 15px;
            flex: 0 0 33%;
          }
        }
      }

      .topTitle {
        font-size: 24px;
        font-family: PingFangSC, PingFang SC;
        font-weight: bold;
        margin-bottom: 20rem;
      }

      .centerRemark {
        display: flex;
        align-items: flex-start;
        width: 800px;
        min-height: 200px;
        background-color: #d5e2d8;
        margin-bottom: 30rem;
        padding: 20px;

        .iconStyle {
          margin-right: 5rem;
          margin-top: 2px;
          color: #5fb17f;
        }

        .spanStyle {
          margin-right: 5rem;
          font-weight: bold;
          font-family: PingFangSC, PingFang SC;
        }
      }

      .bottomTable {
        width: 100%;
        height: auto;
        background-color: #fff;

        .tableNav,
        .tableType {
          display: flex;
          min-height: 50px;
          border-top: 1px solid #797979;
          border-left: 1px solid #797979;
          border-bottom: 1px solid #797979;

          .nav1 {
            flex-direction: column;
            flex: 0 0 13%;
            border-right: 1px solid #797979;
            @include CommonFont;
            @include CommonNav;
            padding: 10px;
            text-align: center;
          }

          .nav2 {
            flex: 1;
            border-right: 1px solid #797979;
            @include CommonFont;
            @include CommonNav;
            padding: 10px;
          }

          .errorText {
            display: flex;
            justify-content: flex-start;
            width: 100%;
            color: red;
            font-size: 14px;
            margin-top: 5px;
          }
        }

        .tableType {
          border-top: none !important;
        }
      }
    }
  }
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
